package com.sayice.coursetable.logic.network;

import com.alibaba.fastjson2.JSON;

import java.io.IOException;
import java.util.Objects;

import okhttp3.Request;
import okhttp3.Response;

/**
 * 专业相关服务
 */
public abstract class MajorService {
    private static final String MAJOR_URL = "http://jwgl.csuft.edu.cn/jsxsd/kbcx/getZyByAjax?sknj=";

    /**
     * 获取专业列表
     *
     * @param username 用户名
     * @param password 密码
     * @param grade    年级（入学年份）
     * @return 返回专业列表的 json 字符串，若获取失败则返回 null
     */
    public static String getMajors(String username, String password, int grade) {
        return LoginService.requestHtml(username, password, httpClient -> {
            String majorsJson = null;
            Request weekRequest = new Request.Builder().url(MAJOR_URL + grade).get().build();
            try (Response majorResponse = httpClient.newCall(weekRequest).execute()) {
                majorsJson = Objects.requireNonNull(majorResponse.body()).string();
                if (!JSON.isValid(majorsJson)) {
                    majorsJson = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return majorsJson;
        });
    }
}
